<?
/**
 *订单记录类.
 *查询订单详情和处理订单的相关操作.
 */
class OrderRecord{
    /**
     *订单号.
     *var int
     */
    protected $ordernum;

    /**
     *票付通内部接口对象
     *@var object
     */
    protected $s;

    /**
     *键值数组对应UUstatus文本和样式
     *@static
     *@var array
     */
    public static $UUstatusT=array(0=>"未使用",1=>"<em class='green'>已使用</em>",2=>"已过期",3=>"<em class='red'>已取消</em>",4=>"被替代",5=>"被修改",6=>"已撤销",7=>"部分使用");

    /**
     *键值数组对应UUstatus文本和样式
     *@static
     *@var array
     */
    public static $statusT=array("0"=>"未使用","1"=>"<em class='green'>已使用</em>","2"=>"<em class='gray'>已过期</em>","3"=>"<em class='red'>已取消</em>","4"=>"凭证码被替代","6"=>"被终端撤销</br><em class='red'>(已取消)</em>","5"=>"被终端修改</br><em class='green'>(已使用)</em>");

    public static $_nSStatusT=array("0"=>"未使用","1"=>"已使用","2"=>"已过期","3"=>"已取消","4"=>"凭证码被替代","6"=>"被终端撤销</br>(已取消)","5"=>"被终端修改----(已使用)");

    /**
     *键值数组对应UUpmode文本和样式
     *@static
     *@var array
     */
    public static $paymodeT=array(0=>"账户余额",1=>"支付宝",2=>"授信支付",3=>"产品自销",4=>"现场支付",5=>"微信支付");

    /**
     *键值数组对应UUpaystatus文本和样式
     *@static
     *@var array
     */
    public static $paystatusT=array(1=>"<em class='green'>(已支付)</em>",2=>"<em class='orange'>(待支付)</em>");

    /**
     *键值数组对应门票产品类型
     *@static
     *@var array
     */
    public static $p_typeT=array("A"=>"门票","B"=>"线路","C"=>"酒店","D"=>"商品","F"=>"套票");

    /**
     *构造函数.
     *@param int $ordernum 订单号
     *@param object 票付通内部接口对象
     */
    public function __construct($ordernum, $s){
        $this->ordernum=$ordernum;
        $this->s=$s;
    }

    /**
     *格式化订单记录函数.
     *联票订单将以存在主订单和从订单，非联票订单制存在主订单
     *@param object simplexml对象
     *@return array
     */
    public static function format($simxml){
        $info=array();
        $info['childOrder']=array();
        $info['orderAlipay']=false;
        $info['orderCancel']=false;
        $info['orderAlter'] =false;
        $count=count($simxml);
        foreach($simxml as $row){
            if($count>1){
                if((string)$row->UUconcat_id===(string)$row->UUordernum){
                    $info['mainOrder'] = $row;
                }else{
                    $info['childOrder'][]=$row;
                }
            }
            else{
                $info['mainOrder']=$row;
            }
            $info['totalPrice'] +=(string)$row->UUtotalmoney;
            $info['totalTnum']  +=(string)$row->UUtnum;
            $info['totalOrder']++;
        }
        $paystatus = (string)$info['mainOrder']->UUpaystatus;
        $status = (string)$info['mainOrder']->UUstatus;
        $buyid = (string)$info['mainOrder']->UUbuyid;
        $pmode = (int)$info['mainOrder']->UUpmode;
        $contacttel = (string)$info['mainOrder']->UUcontacttel;
        $aid = (string)$info['mainOrder']->UUaid;
        // 购买人支付未支付订单（支付宝订单）
        if($pmode==1 && $paystatus!=1 && $status==0 && $buyid==$_SESSION['sid']){
            $info['orderAlipay']=true;
        }
        // 散客未支付可取消
        if($contacttel == $_SESSION['account']) $info['orderCancel']=true;

        // 散客支付完有修改权限
        if($contacttel == $_SESSION['account'] && $paystatus==1){
            $info['orderAlter']=true;
        }
        // 平台订单并且已支付
        if($info['mainOrder']->UUremotenum==0 && $paystatus==1){
            // 购买人有修改和重发权限()
            $fit = in_array((int)$info['mainOrder']->UUordermode,array(1,2));
            if($status==0 && $buyid==$_SESSION['sid'] && !$fit){
                $info['orderAlter']=true;
                $info['orderResend']=true;
                $info['orderCancel']=true;
            }
            // 已过期可以取消
            if($status==2 && $buyid==$_SESSION['sid'] && !$fit){
                $info['orderCancel']=true;
            }

            // 已过期最下级卖家可以取消
            if($status==2 && $aid==$_SESSION['sid'] && !$fit){
                $info['orderCancel']=true;
            }
        }

        // 平台订单可以取消
        if((string)$info['mainOrder']->UUordername=='淘宝码商' && $paystatus==1){
            $fit = in_array((int)$info['mainOrder']->UUordermode,array(1,2));
            if($status==0 && $buyid==$_SESSION['sid'] && !$fit){
                $info['orderCancel']=true;
            }
        }



        // 未支付并且是购买者给取消权限
        if($paystatus==2 && $status==0 && $buyid==$_SESSION['sid']){
            $info['orderCancel']=true;
        }

        // 现场支付（包含自销）
        if( ($pmode==4 || $pmode==3) && (int)$info['mainOrder']->UUstatus==0){
            $info['orderAlter'] =1;
            $info['orderCancel']=1;
            $info['orderResend']=1;
        }
        return $info;
    }
    /*订单操作（查看，修改，重发，取消,支付）权限*/
    /**
     *格式化订单记录函数.
     *联票订单将以存在主订单和从订单，非联票订单制存在主订单
     *@param object simplexml对象
     *@return array
     *说明：童改写，解决订单号查询时没有从订单。不改变源码做冗余；
     */
    public static function _format($simxml,$other){
        $info=array();
        $info['childOrder']=array();
        $info['orderAlipay']=false;
        $info['orderCancel']=false;
        $info['orderAlter']=false;
        $count=count($simxml);
        // echo $count;
        // print_r($other);
        // exit;
        foreach($simxml as $row){
            if($count>1){
                if($row->UUifpack>0){
                    if($row->UUifpack==1){
                        $info['mainOrder']=$row;
                    }else{
                        $info['packOrder'][]=$row;
                        continue;
                    }
                }else{
                    if($row->UUconcat_id=="main"){
                        $info['mainOrder']=$row;

                    }else{
                        $info['childOrder'][]=$row;
                    }
                }
            }else{
                // echo "我来也";
                $info['mainOrder']=$row;
                if(count($other)){
                    $info['childOrder'][]=$other;
                }
            }
            $info['totalPrice']+=(string)($row->UUtnum*$row->UUtprice);
            $info['totalTnum']+=(string)$row->UUtnum;
            $info['totalOrder']++;
            if(count($other)){
                $info['totalOrder']+=count($other);
                $info['totalPrice']+=(string)($other->UUtnum*$other->UUtprice);
            }
        }
        if($info['mainOrder']->UUpmode==1&&$info['mainOrder']->UUpaystatus!=1 && $info['mainOrder']->UUstatus==0){
            $info['orderAlipay']=true;
        }

        if($info['mainOrder']->UUremotenum==0 && (int)$info['mainOrder']->UUpaystatus==1){

            if(in_array((int)$info['mainOrder']->UUstatus,array(0))){
                $info['orderAlter']=true;
                $info['orderResend']=true;
            }
            if(in_array((int)$info['mainOrder']->UUstatus,array(0,2))){
                $info['orderCancel']=true;
            }

        }
        //现场支付
        if((int)$info['mainOrder']->UUpmode==4 && (int)$info['mainOrder']->UUstatus==0){
            $info['orderAlter'] =1;
            $info['orderCancel']=1;
            $info['orderResend']=1;
        }

        return $info;
    }

    /**
     *订单操作权限查询函数.
     *查看用户是否有订单操作权限
     *@param int $order 订单号
     *@param int $did 操作人ID
     *@param int $account 普通用户账号，机预订手机号
     *@param string $auth 需查询权限字段 orderView,orderCancel,orderAlter,orderChange
     *@return array
     */
    public static function orderOperAuth($order,$did,$account="",$auth){
        if($auth=="orderView"){
            if($did==(string)$order['mainOrder']->UUmid || $did==(string)$order['mainOrder']->UUaid||$did==1)
                return true;
        }
        if($auth=="orderAlter" || $auth=="orderCancel" || $auth=='orderResend' ){ // 先行同步的 现场支付的 不让取消和修改
            if((string)$order['mainOrder']->UUpaystatus==0 && strpos('a'.(string)$order['mainOrder']->UUremotenum,'16u_')>0||$row['mainOrder']->UUstatus==2&&$row['mainOrder']->UUpaystatus==1) return false;
        }
        // 先行同步的不让取消和修改
        if($auth=="orderAlter" || $auth=="orderCancel" || $auth=='orderResend' ){
            if((string)$order['mainOrder']->UUsync_status==2 && (string)$order['mainOrder']->UUremotenum!=0) return false;
        }
        if ($auth == 'orderResend' && $order[$auth]) {
            //散客订单可由原始供应商发送短信——Guangpen Chen Add It.
            $idArr = array(
                (int)$order['mainOrder']->UUsellid,
                (int)$order['mainOrder']->UUaid,
                (int)$order['mainOrder']->UUmid
            );
            if(in_array($did , $idArr)) return true;
        }
        else {

            if((int)$order['mainOrder']->UUordermode==0 && $order[$auth]){//分销下单权限
                if($did==(int)$order['mainOrder']->UUmid || $did==(int)$order['mainOrder']->UUsellid)
                    return true;
            }
        }

        if((int)$order['mainOrder']->UUordermode==0 && $order[$auth]){//分销下单权限
            if($did==(int)$order['mainOrder']->UUmid || $did==(int)$order['mainOrder']->UUsellid)
                return true;
        }

        $fit = in_array((int)$order['mainOrder']->UUordermode,array(1,2));

        if( $fit && $order[$auth]){// 普通用户下单
            if($account==(string)$order['mainOrder']->UUcontacttel) return true;

        }


        $paystatus = (int)$order['mainOrder']->UUpaystatus;
        $usestatus = (int)$order['mainOrder']->UUstatus;


        // 自己购买未支付可取消
        if(($paystatus==2)&&($usestatus==0) && $order[$auth]) return true;

        // 散客已支付可修改
        if(($paystatus==1)&&($usestatus==0) && $order[$auth] && $fit) return true;
        return false;
    }

    /**
     *查询订单数据.
     *联票也一同被返回,故有可存在对个simplexml对象
     *@return object
     */
    public function info_bk($ifpack=1,$concat_id=0){
        //$ifpack=1;
        $xml=$this->s->Order_Globle_Search("","","","","","","","","","","","",
            $this->ordernum,"","","","","",1,1,0,999,"","","","","","","","","",
            $concat_id,$ifpack);

        $simxml = simplexml_load_string($xml);
        //TODO::套票订单，查询子订单
        if ($simxml->Rec->UUp_type=='F') {
            $info['mainOrder'] = $simxml->Rec;
            $info['totalPrice'] =$simxml->Rec->UUtotalmoney;
            $info['totalTnum']  =$simxml->Rec->UUtnum;
            $xmlChildOrders = $this->s->Order_Globle_Search("","","","","","",
                "","","","","","",$this->ordernum,"","","","","",1,1,0,999,"",
                "","","","","","","","",0,2);
            if ($_GET['cgp']) {

                echo '===============';
                echo $xmlChildOrders;
            }

            $simxml2 = simplexml_load_string($xmlChildOrders);
//            echo $xmlChildOrders;
            foreach($simxml2 as $r2) {
                $info['childOrder'][] = $r2;
            }
            return $info;
        }
        else {
//            return $this->format($simxml->Rec);
            return $this->format($simxml->Rec);
        }
    }

    public function info($ifpack=1,$concat_id=0){
        // 
        // $buyid = ($_REQUEST['from']=='buy' && $_SESSION['dtype']!=9 && $_SESSION['dtype']!=5 && $_SESSION['dtype']!=2) ? $_SESSION['sid']:'';
        // $saleid = ($_REQUEST['from']=='sale' && $_SESSION['dtype']!=9 && $_SESSION['dtype']!=5 && $_SESSION['dtype']!=2) ? $_SESSION['sid']:'';
        $buyid='';
        $saleid='';
        $xml=$this->s->Order_Globle_Search("",$buyid,"","","","","","","","","","",$this->ordernum,"","","","","",1,1,0,1,"","","","","","","","",$saleid,0,1);
        $simxml = simplexml_load_string($xml);
        //TODO::套票订单，查询子订单
        if ($simxml->Rec->UUp_type=='F') {
            $info['mainOrder'] = $simxml->Rec;
            $info['totalPrice'] =$simxml->Rec->UUtotalmoney;
            $info['totalTnum']  =$simxml->Rec->UUtnum;
            $xmlChildOrders = $this->s->Order_Globle_Search("","","","","","", "","","","","","",$this->ordernum,"","","","","",1,1,0,999,"", "","","","","","","","",0,2);
            $simxml2 = simplexml_load_string($xmlChildOrders);
            foreach($simxml2 as $r2) {
                $info['childOrder'][] = $r2;
            }
            return $info;
        }else{  // 如果 UUconcat_id 不为 0 表示复票
            if($simxml->Rec->UUconcat_id!=0 && (string)$simxml->Rec->UUconcat_id==(string)$simxml->Rec->UUordernum){
                $xml=$this->s->Order_Globle_Search("",$buyid,"","","","","","","","","","",$this->ordernum,"","","","","",1,1,0,999,"","","","","","","","",$saleid,1,0);
            }
            $simxml = simplexml_load_string($xml);
        }
        return $this->format($simxml->Rec);
    }

    // 林俊接口去掉 group by 导致不传 $buyid 返回多条信息
    public function info_n($mid='',$aid=''){
        // 先找主订单
        $xml=$this->s->Order_Globle_Search("",$mid,"","","","","","","","","","",$this->ordernum,"","","","","",1,1,0,1,"","","","","","","","",$aid,0,1);
        $simxml = simplexml_load_string($xml);
        //TODO::套票订单，查询子订单
        if ($simxml->Rec->UUp_type=='F') {
            $info['mainOrder'] = $simxml->Rec;
            $info['totalPrice'] =$simxml->Rec->UUtotalmoney;
            $info['totalTnum']  =$simxml->Rec->UUtnum;
            $xmlChildOrders = $this->s->Order_Globle_Search("","","","","","", "","","","","","",$this->ordernum,"","","","","",1,1,0,15,"", "","","","","","","","",0,2);
            $simxml2 = simplexml_load_string($xmlChildOrders);
            foreach($simxml2 as $r2) {
                $info['childOrder'][] = $r2;
            }
            return $info;
        }else{  // 如果 UUconcat_id 不为 0 表示复票
            if($simxml->Rec->UUconcat_id!=0 && (string)$simxml->Rec->UUconcat_id==(string)$simxml->Rec->UUordernum){
                $xml=$this->s->Order_Globle_Search("",$mid,"","","","","","","","","","",$this->ordernum,"","","","","",1,1,0,15,"","","","","","","","",$aid,1,0);
            }
            $simxml = simplexml_load_string($xml);
        }
        return $this->format($simxml->Rec);
    }


    /**
     *订单取消函数.
     *联票也一同被返回,故有可存在对个simplexml对象
     *@return bool 成功返回true
     */
    public function cancel($operator, $concat_id=0, $orders=array()){

        // $orders= $concat_id ? $this->info(0, 1):$this->info();
        $orders= count($orders) ? $orders : $this->info_n($_SESSION['sid']);
        $array=array();
        $array[] = $orders['mainOrder'];
        if($orders['mainOrder']->UUordermode==0){
            if($operator!=$orders['mainOrder']->UUaid){// 非最下级销售者
                if($operator!=$orders['mainOrder']->UUmid) throw new Exception("非自身订单，无权取消");
            }
        }
        else{
            if (isset($_SESSION['mobile']) && !empty($_SESSION['mobile'])) {
                $account = $_SESSION['mobile'];
            } else {
                $str="select account from pft_member where id=$operator limit 1";
                $GLOBALS['le']->query($str);
                $GLOBALS['le']->fetch_assoc();
                $account = $GLOBALS['le']->f("account");
            }

            if( $account !=(string)$orders['mainOrder']->UUcontacttel)
                throw new Exception("非游客自身订单，无权取消{$account}--{$orders['mainOrder']->UUcontacttel}");
        }
        if ($orders['mainOrder']->UUp_type=='F' || $orders['mainOrder']->UUconcat_id==0) {
            $tuikuan = ((string)$orders['mainOrder']->UUpaystatus==2 || (string)$row->UUstatus==2) ? 1:0;
            $res = $this->s->Order_Change_Pro((string)$orders['mainOrder']->UUordernum,0,-1,$tuikuan,$operator);
            if($res!=100) return array("code"=>101,"msg"=>$res);
        }
        else {
            $array = array_merge($orders['childOrder'], $array);

            foreach($array as $row){
                // 过期跟未支付不退款
                $tuikuan = ((string)$row->UUpaystatus==2 || (string)$row->UUstatus==2) ? 1:0;
                $res = $this->s->Order_Change_Pro((string)$row->UUordernum,0,-1,$tuikuan,$operator);
                if($res!=100) return array("code"=>101,"msg"=>$res);
            }
        }

        return array("code"=>100,"msg"=>$res);
    }

    /**
     * 重发短信函数
     *      update:2015-03-22 11:27:12 by Guangpeng Chen
     * @param null $orders
     * @return mixed
     */
    public function resendMsg($orders=null){

        if (is_null($orders)) {
            $orders = $this->info();
        }

        include '/var/www/html/new/d/class/OrderSmsManual.class.php';
        $smsManual  = new \PFT\SMS\OrderSmsManual($this->s);
        $ret = $smsManual->SendByOrderInfo($orders, false);
        return $ret==100 ? true : false;
//        return $this->s->reSend_SMS_Global_PL(
//            (string)$orders['mainOrder']->UUordernum,
//            (string)$orders['mainOrder']->UUaid,
//            (string)$orders['mainOrder']->UUmid);//最后重发短信
    }



    /**
     *修改订单门票数函数.
     *@param int $tid 门票ID
     *@param int $tnum 门票数
     *@param int $operator 操作人ID
     *@return bool 成功返回true
     */
    public function changeTnum($tid,$tnum,$operator, $orders=array()){
        if(empty($orders)){
            $orders = $this->info();
        }
        $array=array();
        $array[]=$orders['mainOrder'];
        if($orders['mainOrder']->UUordermode==0){
            if($operator!=$orders['mainOrder']->UUmid) throw new Exception("非自身订单，无权修改数量");
        }else{
            $str="select account from pft_member where id=$operator";
            $GLOBALS['le']->query($str);
            $GLOBALS['le']->fetch_assoc();
            if($GLOBALS['le']->f("account")!=(string)$orders['mainOrder']->UUcontacttel)
                throw new Exception("非游客自身订单，无权修改数量");
        }
        $array=array_merge($array,$orders['childOrder']);
        foreach($array as $row){
            if((string)$row->UUtid==$tid&&$tnum<(string)$row->UUtnum){
                $totalprice=(float)$row->UUtprice*$tnum;
                $ret = $this->s->Order_Change_Pro((string)$row->UUordernum,$tnum,$totalprice,0,$operator);
                print_r($ret);
                if($ret!=100){
                    // echo $ret;
                    return array("code"=>101,"msg"=>$ret);
                }
            }
        }
        return array("code"=>100,"msg"=>$ret);
    }

    /**
     * 修改订单游玩时间函数.
     *
     * @param $begintime 游玩时间
     * @param $operator 操作人ID
     * @param array $orders 订单数据（Guangpeng Chen Add It.）
     * @return bool
     * @throws Exception
     */
    public function changeBegintime($begintime,$operator, $orders=array()){
        if(empty($orders)){
            $orders = $this->info();
        }
        $array[]=$orders['mainOrder'];
        if ($orders['mainOrder']->UUordermode==0 &&
            $operator!=$orders['mainOrder']->UUmid)
        {
            throw new Exception("非自身订单，无权修改时间");
        }
        else {
            // $str="select account from pft_member where id=$operator";
            // $GLOBALS['le']->query($str);
            // $GLOBALS['le']->fetch_assoc();
            // if($GLOBALS['le']->f("account")!=(string)$orders['mainOrder']->UUordertel)
            if($operator!=(string)$orders['mainOrder']->UUbuyid && (string)$orders['mainOrder']->UUremotenum!=0 && ((string)$orders['mainOrder']->UUconcat_id!=0 && (string)$orders['mainOrder']->UUconcat_id!=(string)$orders['mainOrder']->UUordernum))
                throw new Exception("非游客自身订单，无权修改时间");
        }
        $times=strtotime($orders['mainOrder']->UUendtime) - strtotime($orders['mainOrder']->UUbegintime);
//        $times=strtotime($orders['mainOrder']->UUendtime-$UUbegintime);
        $array=array_merge($array,$orders['childOrder']);
        $endtime=date("Y-m-d H:i:s",strtotime($begintime)+$times);
        foreach($array as $row){
            $this->s->Order_Change_Pro((string)$row->UUordernum,-1,-1,1,$operator,$begintime,$endtime);
        }
        return true;
    }

    /**
     *未支付订单支付函数.
     *将处理订单的分润数据，并跳的支付宝支付
     */
    public function alipay(){
        $orderInfo=$this->info();

        $orderid=(string)$orderInfo['mainOrder']->UUordernum;
        $title=($orderInfo['mainOrder']->UUltitle).($orderInfo['mainOrder']->UUttitle);
        $money=$orderInfo['totalPrice']/100;
        $url="http://www.12301.cc/scenicDetail.html?lid=".$orderInfo['mainOrder']->UUlid;

        $mid=(string)$orderInfo['mainOrder']->UUmid;
        $str="select alipay from pft_member where id=$mid";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        $alicount=$GLOBALS['le']->f("alipay");
        $describe="分销商预订".$title;

        $apply_did=(string)$orderInfo['mainOrder']->UUaid;
        $str="select alipay,fee_bank from pft_member where id=$apply_did limit 1";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        $fee_bank=$GLOBALS['le']->f("fee_bank")/1000;

        $acount1=$GLOBALS['le']->f("alipay");
        $money1 = $orderInfo['totalPrice']*(1-$fee_bank);
        $clearDesc1="供应商".$title ."(".$orderid.")分润";
        $acount2="";
        $money2="";
        $clearDesc2="";


//        if($orderInfo['mainOrder']->UUordermode==1
//            &&(string)$orderInfo['mainOrder']->UUmid!=(string)$orderInfo['mainOrder']->UUaid){//普通用户下单
//            $mid=(string)$orderInfo['mainOrder']->UUmid;
//            $str="select alipay from pft_member where id=$mid";
//            $GLOBALS['le']->query($str);
//            $GLOBALS['le']->fetch_assoc();
//            $acount2=$GLOBALS['le']->f("alipay");
//            $money2=0;
//            $clearDesc2="分销商".$title ."(".$orderid.")分润";
//            /*分销商利润*/
//            $orders=array(0=>$orderInfo['mainOrder']);
//            $orders=array_merge($orders,$orderInfo['childOrder']);
//            foreach($orders as $row){
//                $mid=(string)$row->UUmid;
//                $pid=(string)$row->UUpid;
//                $pro=new ProductInfo($pid,$this->s);
//                //分销权限判定
//                if(!$pro->supply($mid)) return false;
//                if((string)$row->UUaprice==0) return false;
//                $dprice = $pro->dprice($mid);
//                $money2 += ((string)$row->UUtprice-(string)$row->UUaprice-$dprice)*(string)$row->UUtnum;
//            }
//            /*供应商利润*/
//            $money1=($money1-$money2);
//        }
        $a_key[]='WIDout_trade_no';
        $a_key[]='WIDsubject';
        $a_key[]='WIDtotal_fee';
        $a_key[]='WIDbody';
        $a_key[]='WIDshow_url';
        $a_key[]='WIDbuyer';

//        $a_key[]='WIDaccount1';
//        $a_key[]='WIDpay1';
//        $a_key[]='WIDpay1txt';
//        $a_key[]='WIDaccount2';
//        $a_key[]='WIDpay2';
//        $a_key[]='WIDpay2txt';

        $a_key[]='return_url';
        $a_key[]='notify_url';

        $a_value[]=$orderid;//商户订单号,商户网站订单系统中唯一订单号，必填
        $a_value[]=$title;//订单名称或产品名称，必填
        $a_value[]=$money;//付款金额，必填
        $a_value[]=$describe;//订单描述
        $a_value[]=$url;//产品展示路径 例如：http://www.12301.cc/s_01.html
        $a_value[]=$alicount;//买家绑定的支付宝帐号 最好填上

//        $a_value[]=$acount1;//分润帐号1
//        $a_value[]=$money1;//分润1金额 分单位
//        $a_value[]=$clearDesc1;//分润1描述
//        $a_value[]=$acount2;//分润帐号2
//        $a_value[]=$money2;//分润2金额 分单位
//        $a_value[]=$clearDesc2;//分润2描述

        $a_value[]="http://www.12301.cc/alipay/ali_order/return_url.php";
        $a_value[]="http://www.12301.cc/alipay/ali_order/notify_url.php";
        // if($_SESSION['sid']==83){
        // $a_value[]="http://www.12301.cc/alipay/ali_order/notify_url_dev.php";
        // }else{
        // $a_value[]="http://www.12301.cc/alipay/ali_order/notify_url.php";
        // }
        /*print_r(array_combine($a_key,$a_value));
        exit;*/
        $this->make_post($a_key,$a_value);
    }
    public function alipayMobile(){
        $orderInfo=$this->info();
        $orderid=(string)$orderInfo['mainOrder']->UUordernum;
        $title=($orderInfo['mainOrder']->UUltitle).($orderInfo['mainOrder']->UUttitle);
        $money=$orderInfo['totalPrice']/100;

        $a_key[]='WIDout_trade_no';//商户订单号
        $a_key[]='WIDsubject';//订单名称
        $a_key[]='WIDtotal_fee';//付款金额

        $a_value[] = $orderid;//商户订单号,商户网站订单系统中唯一订单号，必填
        $a_value[] = $title;//订单名称或产品名称，必填
        $a_value[] = $money;//付款金额，必填
        $this->make_post($a_key,$a_value, 'http://wx.12301.cc/pay/alipay_v3.3/alipayapi.php');
    }

    /**
     * 未支付订单支付提交函数.
     *  2014年11月25日11:16:44，Updated By Guangpeng Chen.Add Post Url param.
     * @uses OrderRecord::alipay
     * @param $id
     * @param $vid
     * @param null $url
     * @return mixed
     */
    public static function make_post($id, $vid, $url= null){
        $post_data = array();
        if (!is_array($id) && !is_array($vid)){
            $post_data[$id] = $vid;
        }else{
            $post_data = array_combine($id, $vid);
//        foreach ($id as $kk=>$vv){
//        $post_data[$vv]=$vid[$kk];
//        }
        }
        $url= is_null($url) ? 'http://pay.12301.cc/alipayapi.php' : $url;
//        $o ="";
        $post_data = http_build_query($post_data);

//        foreach ($post_data as $k=>$v){
//        $o.= "$k=".urlencode($v)."&";
//        }
//        $post_data=substr($o,0,-1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,0);
        return curl_exec($ch);
    }

    /**
     * 使用IPS支付
     *
     * @return bool
     */
    public function ipsPay()
    {
        $orderInfo = $this->payCommon();
        $payDate   = date('Ymd');
        $Amount = number_format($orderInfo['money'], 2, '.', '');
        //IPS证书
        $key = '7667659191929397103470329788807862402627565924638280479623896'.
            '0393156885586815305050516493889730425518949732797083380078766300585';
        $sign      = 'billno'.$orderInfo['orderid'].'currencytypeRMBamount'
            .$Amount.'date'.$payDate.'orderencodetype5'.$key;
        $signMd5   = md5($sign);
        $Bankco = $_REQUEST['Bankco'];
        $payParams = array(
            'Mer_code'  => '026188',
            'Billno'    => $orderInfo['orderid'],
            'Amount'    => $Amount,
            'Date'      => $payDate,
            'Currency_Type' => 'RMB',
            'Gateway_Type'  => '01',
            'Lang'      => 'GB',
            'Merchanturl'   => 'http://www.12301.cc/ips/ips_return_url.php',
            'FailUrl'   => '',
            'ErrorUrl'  => '',
            'Attach'    => '支付订单'.$orderInfo['orderid'],//商户数据包
            'DispAmount'    => '',
            'OrderEncodeType'   => 5,//订单支付接口加密方式
            'RetEncodeType' => 17,
            'Rettype'   => 1,
            'ServerUrl' => 'http://www.12301.cc/ips/ips_notify_url.php',
            'SignMD5'   => $signMd5,
            'DoCredit'  => 1,
            'Bankco'    => $Bankco,
        );

        echo $this->buildPayForm('https://pay.ips.com.cn/ipayment.aspx', $payParams);
        return true;
    }

    /**
     * 构建支付表单
     *
     * @param string $url 提交地址
     * @param array $data  提交的数据
     * @return mixed
     */
    public function buildPayForm($url, Array $data)
    {
        $html = <<<HTML
<html>
  <head>
    <title>跳转......</title>
    <meta http-equiv="content-Type" content="text/html; charset=utf-8" />
  </head>
  <body>
   <form action="{$url}" method="post" id="frm1">
   {inputField}
   </form>
   <script language="javascript">
      document.getElementById("frm1").submit();
    </script>
  </body>
</html>
HTML;
        $inputField = '';
        foreach($data as $key=>$val) {
            $inputField .= "<input type='hidden' name='{$key}' value='{$val}'/>";
        }
        return str_replace('{inputField}', $inputField, $html);
    }

    /**
     * 订单数据
     *
     * @return array|bool
     */
    public function payCommon()
    {
        $orderInfo=$this->info();
        $orderid=(string)$orderInfo['mainOrder']->UUordernum;
        $title=($orderInfo['mainOrder']->UUltitle).($orderInfo['mainOrder']->UUttitle);
        $money=$orderInfo['totalPrice']/100;
        $url="http://www.12301.cc/scenicDetail.html?lid=".$orderInfo['mainOrder']->UUlid;

        $mid=(string)$orderInfo['mainOrder']->UUmid;
        $str="select alipay from pft_member where id=$mid";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        $alicount=$GLOBALS['le']->f("alipay");
        $describe="分销商预订".$title;

        /*****分润1******/
        $apply_did=(string)$orderInfo['mainOrder']->UUaid;
        $str="select alipay,fee_bank from pft_member where id=$apply_did";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        $fee_bank=$GLOBALS['le']->f("fee_bank")/1000;
//            $acount1=$GLOBALS['le']->f("alipay");
        $money1 = $orderInfo['totalPrice']*(1-$fee_bank);//对应$apply_did

        $clearDesc1 = "供应商".$title ."(".$orderid.")分润";
        $money2     = 0;
        $clearDesc2 = "";
        if($orderInfo['mainOrder']->UUordermode==1
            &&(int)$orderInfo['mainOrder']->UUmid!=(int)$orderInfo['mainOrder']->UUaid){//普通用户下单

            $money2=0; //对应(int)$orderInfo['mainOrder']->UUmid
            $clearDesc2="分销商" . $title ."(".$orderid.")分润";
            /*分销商利润*/
            $orders=array(0=>$orderInfo['mainOrder']);
            $orders=array_merge($orders, $orderInfo['childOrder']);
            foreach ($orders as $row){
                $mid = (int)$row->UUmid;
                $pid = (int)$row->UUpid;
                $pro = new ProductInfo($this->s, $pid);
                //分销权限判定
                if(!$pro->supply($mid)) return false;
                if((float)$row->UUaprice==0) return false;
                $dprice = $pro->dprice($mid);
                $money2 += ($row->UUtprice - $row->UUaprice - $dprice) * (int)$row->UUtnum;
            }
            /*供应商利润*/
            $money1     = ($money1-$money2);
        }
        //TODO:供应商分润
        $royalty_parameters = "$apply_did^$money1^$clearDesc1";
        //TODO:散客购买，分销商分润
        if($money2>0) {
            $mid2 = (int)$orderInfo['mainOrder']->UUmid;
            $royalty_parameters .= "|$mid2^$money2^$clearDesc2";
        }
        //TODO:支付记录,先判断是否存在记录
        $sql_chk = "SELECT id FROM pft_ips_rec WHERE out_trade_no='{$orderid}'";
        $GLOBALS['le']->query($sql_chk);
        $res = $GLOBALS['le']->fetch_assoc();
        if(!$res['id']) {
            $sql_log_ips = "INSERT INTO pft_ips_rec(fid,royalty_parameters,".
                " total_fee, out_trade_no,subject) VALUES($mid,'$royalty_parameters',".
                "{$orderInfo['totalPrice']},'$orderid','$describe')";
            $GLOBALS['le']->query($sql_log_ips);
        }

        return compact('orderid', 'title', 'money', 'describe', 'url',
            'alicount', 'acount1', 'money1', 'clearDesc1', 'acount2',
            'money2', 'clearDesc2');
    }
}
?>